<template>
  <div class="layer-container" :class="{ collapsed: !isExpanded }">
    <!-- 收起按钮 -->
    <button class="toggle-button" @click="toggleLayer">
      {{ isExpanded ? "<" : ">" }}
    </button>
    <!-- 使用单个容器包裹所有项目，并使用flexbox进行布局 -->
    <div v-if="isExpanded" class="items-container">
      <div v-for="(item, index) in items" :key="index" class="item-row">
        <el-checkbox
          v-model="item.checked"
          class="checkbox"
          @change="layerhandle(item, 999)"
        ></el-checkbox>
        <div
          class="layer-text"
          :class="{ 'checked-layer': item.checked }"
          @click="layerhandle(item, index)"
        >
          {{ item.text }}
        </div>
      </div>
    </div>
  </div>
  <div>
    <el-button
      @click="zoomIn"
      @mousedown="zoomInMouseDown"
      @mouseup="myMouseUp"
      style="
        position: absolute;
        z-index: 9999;
        left: 330px;
        top: 220px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      >+</el-button
    >
    <el-button
      @click="check3D"
      style="
        position: absolute;
        z-index: 9999;
        left: 318px;
        top: 250px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      >{{ checkLabel }}</el-button
    >
    <el-button
      @click="zoomOut"
      @mousedown="zoomOutMouseDown"
      @mouseup="myMouseUp"
      style="
        position: absolute;
        z-index: 9999;
        left: 318px;
        top: 280px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      >-</el-button
    ><el-button
      @click="zoomToOriginal"
      style="
        position: absolute;
        z-index: 9999;
        left: 318px;
        top: 310px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      >复位</el-button
    >
  </div>
  <div v-if="windData" class="wind-data-display">
    <h3>海流信息</h3>
    <p>经度: {{ windData.lon }}</p>
    <p>纬度: {{ windData.lat }}</p>
    <h4>插值数据</h4>
    <p>流速: {{ windData.interpolated.speed }} m/s</p>
    <p>U 分量: {{ windData.interpolated.u }} m/s</p>
    <p>V 分量: {{ windData.interpolated.v }} m/s</p>
    <h4>原始数据</h4>
    <p>流速: {{ windData.original.speed }} m/s</p>
    <p>U 分量: {{ windData.original.u }} m/s</p>
    <p>V 分量: {{ windData.original.v }} m/s</p>
  </div>
  <div v-if="templatureOrSalt" class="wind-data-display">
    <p>经度: {{ templatureOrSalt.lon }}</p>
    <p>纬度: {{ templatureOrSalt.lat }}</p>
    <p>{{ layerName }}: {{ templatureOrSalt.value }}{{}}</p>
  </div>
  <Colorbar
    v-show="colorbarShow"
    :min="colorMin"
    :max="colorMax"
    :colors="colors"
    :labelCount="labelCount"
  />
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import * as Cesium from "cesium";
import { useEddyStore } from "@/stores/eddyStore";
import { useYuecengStore } from "@/stores/yuecengStore";
import { useCurrentStore } from "@/stores/currentStore";
import { useNeiboStore } from "@/stores/neiboStore";
import Colorbar from "./ColorBar.vue"; // 引入 Colorbar 组件
import windjson from "@/assets/V_20241227.json";
import eddiesData from "@/assets/20220101eddies.json";
import neibodata from "@/assets/neibooutput.json";
import yuecengData from "@/assets/yueceng.json";
import saltData from "@/assets/outputSalt20250220.json";
import fengmianData from "@/assets/outputfengmian.json";
import temperatureData from "@/assets/outputTemperature20250210.json";
import fengmianTemplature from "@/assets/outputfengmian0317.json";
import sla from "@/assets/20220101sla.json";
import { useFengmianStore } from "@/stores/fengmianStore";
import { useData2DStore } from "@/stores/data2DStore";
const data2DStore = useData2DStore();
const fengmianStore = useFengmianStore();
const currentStore = useCurrentStore();
const yuecengStore = useYuecengStore();
const eddyStore = useEddyStore();
const neiboStore = useNeiboStore();
const viewerHandle = ref({});
const currentLayer = ref({});
const colorbarShow = ref(false);
let loadEddy = null;
let checkLabel = ref("2D");
const isPressing = ref(false);
let interval = null;
const windData = ref(null); // 存储海流信息
const templatureOrSalt = ref(null);
const layerName = ref("");
const colorMax = ref(1.23);
const colorMin = ref(0);
const labelCount = ref(10);
const colors = ref([
  "#d61600",
  "#ce2d02",
  "#c64404",
  "#be5b06",
  "#b67208",
  "#ae890a",
  "#a6a00c",
  "#9eb70e",
  "#96ce10",
  "#8ee80e",
]);
const props = defineProps({
  viewerHandle: {
    type: Object,
    required: true,
  },
});
watch(
  () => props.viewerHandle,
  (newValue, oldValue) => {
    viewerHandle.value = props.viewerHandle;
  }
);
// 定义数据
const isExpanded = ref(true); // 控制层是否展开，默认为true（展开）
const items = ref([
  { checked: false, name: "current", type: "current", text: "海流" },
  { checked: false, name: "temperature", type: "temperature", text: "温度" },
  { checked: false, name: "salt", type: "salt", text: "盐度" },
  { checked: false, name: "yueceng", type: "yueceng", text: "跃层" },
  { checked: false, name: "neibo", type: "neibo", text: "内波" },
  { checked: false, name: "eddy", type: "eddy", text: "中尺度涡" },
  { checked: false, name: "fengmian", type: "fengmian", text: "锋面" },
]);
onMounted(async () => {
  viewerHandle.value = props.viewerHandle;
  currentLayer.value = props.currentLayer;
  loadEddy = props.loadEddy;
});
const layerhandle = (data, index) => {
  if (index != 999) {
    items.value[index].checked = !items.value[index].checked;
  }
  // console.log(data);
  console.log(viewerHandle.value);
  switch (data.type) {
    case "temperature":
      hideOherLayer(1);
      data2DStore.setData(temperatureData.data);
      data2DStore.setHeader(temperatureData.header);
      data2DStore.setIsGradient(true);
      layerName.value = "温度";
      let restemplature = getSlaMinMax(temperatureData.data);
      colorMax.value = restemplature.max;
      colorMin.value = restemplature.min;
      data2DStore.minDataValue = restemplature.min;
      data2DStore.maxDataValue = restemplature.max;
      labelCount.value = 10;
      data2DStore.setColors([
        "#0D4D4B",
        "#217A7A",
        "#35A69C",
        "#4BC2BF",
        "#64E9EE",
        "#B2D882",
        "#FFCC00",
        "#FFAE00",
        "#FF9900",
        "#FF0000",
      ]);
      colors.value = [
        "#0D4D4B",
        "#217A7A",
        "#35A69C",
        "#4BC2BF",
        "#64E9EE",
        "#B2D882",
        "#FFCC00",
        "#FFAE00",
        "#FF9900",
        "#FF0000",
      ];
      data2DStore.toggleVisibility();
      window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
      if (data.checked) {
        data.checked = true;
      } else {
        data.checked = false;
      }
      colorbarShow.value = data.checked;

      break;
    case "current":
      currentStore.setWindData(windjson);
      hideOherLayer(0);
      let newdata = processCurrentData(windjson);
      data2DStore.minDataValue = newdata.min;
      data2DStore.maxDataValue = newdata.max;
      data2DStore.setData(newdata.data);
      data2DStore.setHeader(newdata.header);
      data2DStore.setIsGradient(true);
      data2DStore.setColors(["#0D4D4B", "#35A69C", "#64E9EE"]);
      colorMax.value = newdata.max;
      colorMin.value = newdata.min;
      currentStore.setinterpolatedColors(["#ffffff"]);
      colors.value = [
        "#0D4D4B", // 深青蓝
        "#35A69C", // 青蓝
        "#64E9EE", // 浅青蓝
        // "#FFCC00", // 金黄
      ];
      layerName.value = "海流";
      labelCount.value = 6;
      data2DStore.toggleVisibility();
      currentStore.toggleCurrentVisibility(true);
      window.addEventListener("wind-data", handleWindData);
      if (data.checked) {
        data.checked = true;
      } else {
        data.checked = false;
      }
      colorbarShow.value = data.checked;

      break;
    case "salt":
      hideOherLayer(2);
      data2DStore.setData(saltData.data);
      data2DStore.setHeader(saltData.header);
      data2DStore.setIsGradient(true);
      layerName.value = "盐度";
      let resSalt = getSlaMinMax(saltData.data);
      colorMax.value = resSalt.max;
      colorMin.value = 30;
      data2DStore.minDataValue = resSalt.min;
      data2DStore.maxDataValue = resSalt.max;
      labelCount.value = 6;
      data2DStore.setColors([
        "#0D4D4B", // 深青蓝
        "#35A69C", // 青蓝
        "#64E9EE", // 浅青蓝
        "#FFCC00", // 金黄
        "#FF9900", // 橙色
        "#FF0000", // 红色
      ]);
      colors.value = [
        "#0D4D4B", // 深青蓝
        "#35A69C", // 青蓝
        "#64E9EE", // 浅青蓝
        "#FFCC00", // 金黄
        "#FF9900", // 橙色
        "#FF0000", // 红色
      ];
      data2DStore.toggleVisibility();
      window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
      if (data.checked) {
        data.checked = true;
      } else {
        data.checked = false;
      }
      colorbarShow.value = data.checked;
      break;
    case "yueceng":
      hideOherLayer(3);
      yuecengStore.setYuecengData(yuecengData);
      yuecengStore.toggleYuecengVisibility();
      break;
    case "neibo":
      hideOherLayer(4);
      neiboStore.setNeiboData(neibodata);
      neiboStore.toggleNeiboVisibility();
      break;
    case "eddy":
      hideOherLayer(5);
      let res = getSlaMinMax(sla.data);
      data2DStore.minDataValue = res.min;
      data2DStore.maxDataValue = res.max;
      data2DStore.setIsGradient(true);
      data2DStore.setData(sla.data);
      data2DStore.setHeader(sla.header);
      data2DStore.setColors([
        "#0D4D4B", // 深青蓝
        "#35A69C", // 青蓝
        "#64E9EE", // 浅青蓝
        "#FFCC00", // 金黄
        "#FF9900", // 橙色
        "#FF0000", // 红色
      ]);
      colors.value = [
        "#0D4D4B", // 深青蓝
        "#35A69C", // 青蓝
        "#64E9EE", // 浅青蓝
        "#FFCC00", // 金黄
        "#FF9900", // 橙色
        "#FF0000", // 红色
      ];
      colorMax.value = res.max;
      colorMin.value = res.min;
      labelCount.value = 6;
      eddyStore.setEddiesData(eddiesData);
      colorbarShow.value = data.checked;
      eddyStore.toggleEddyVisibility();
      data2DStore.toggleVisibility();
      if (data.checked) {
        data.checked = true;
      } else {
        data.checked = false;
      }
      //
      break;
    case "fengmian":
      hideOherLayer(6);
      let resFengmian = getSlaMinMax(fengmianTemplature.data);
      data2DStore.minDataValue = resFengmian.min;
      data2DStore.maxDataValue = resFengmian.max;
      data2DStore.setIsGradient(true);
      data2DStore.setData(fengmianTemplature.data);
      data2DStore.setHeader(fengmianTemplature.header);
      data2DStore.setColors([
        "#0D4D4B", // 深青蓝
        "#35A69C", // 青蓝
        "#64E9EE", // 浅青蓝
        "#FFCC00", // 金黄
        "#FF9900", // 橙色
        "#FF0000", // 红色
      ]);
      colors.value = [
        "#0D4D4B", // 深青蓝
        "#35A69C", // 青蓝
        "#64E9EE", // 浅青蓝
        "#FFCC00", // 金黄
        "#FF9900", // 橙色
        "#FF0000", // 红色
      ];
      colorMax.value = resFengmian.max;
      colorMin.value = resFengmian.min;
      labelCount.value = 6;
      data2DStore.toggleVisibility();
      fengmianStore.setFengmianCenterData(fengmianData);
      fengmianStore.toggleFengmianVisibility();
      if (data.checked) {
        data.checked = true;
      } else {
        data.checked = false;
      }
      colorbarShow.value = data.checked;
  }
};
const hideOherLayer = (now) => {
  for (let i = 0; i < items.value.length; i++) {
    if (i == now) {
      continue;
    }
    if (items.value[i].checked) {
      switch (i) {
        case 0:
          currentStore.toggleCurrentVisibility(false); //海流
          data2DStore.setIsVisible(true);
          data2DStore.toggleVisibility(); //强度图层
          break;
        case 1:
          data2DStore.setIsVisible(true);
          data2DStore.toggleVisibility(); //强度图层
          break;
        case 2:
          data2DStore.setIsVisible(true);
          data2DStore.toggleVisibility(); //强度图层
          break;
        case 3:
          yuecengStore.setIsVisible(true);
          yuecengStore.toggleYuecengVisibility(); //跃层
          break;
        case 4:
          neiboStore.setIsVisible(true);
          neiboStore.toggleNeiboVisibility(); //内波
          break;
        case 5:
          eddyStore.setIsVisible(true);
          eddyStore.toggleEddyVisibility(); //中尺度涡
          data2DStore.setIsVisible(true);
          data2DStore.toggleVisibility(); //强度图层
          break;
        case 6:
          data2DStore.setIsVisible(true);
          data2DStore.toggleVisibility(); //强度图层
          fengmianStore.setIsVisible(true);
          fengmianStore.toggleFengmianVisibility(); //锋面
          break;
      }
      items.value[i].checked = false;
    }
  }
};
function getSlaMinMax(slaData) {
  // 过滤掉null和NaN值
  const validNumbers = slaData
    .filter((item) => item !== null) // 先过滤掉null值
    .map(Number) // 将字符串转换为数字
    .filter(Number.isFinite); // 过滤掉NaN以及无穷大的值

  if (validNumbers.length === 0) {
    // 如果没有有效数字，根据业务需求决定返回什么
    return { min: NaN, max: NaN };
  }

  // 计算最小值和最大值
  const min = Math.min(...validNumbers);
  const max = Math.max(...validNumbers);

  return { min, max };
}
function processCurrentData(originalArray) {
  // 分离u/v数据组件（根据parameterNumber）
  const [uData, vData] = originalArray.filter((item) =>
    [3, 2].includes(item.header.parameterNumber)
  );
  // 生成强度数据（保留NaN）
  const intensityData = uData.data.map((u, index) => {
    const v = vData.data[index];
    return isNaN(u) || isNaN(v) ? "NaN" : Math.hypot(u, v);
  });

  // 计算最大值和最小值，忽略NaN
  const validIntensityData = intensityData.filter((value) => !isNaN(value));
  const maxIntensity =
    validIntensityData.length > 0 ? Math.max(...validIntensityData) : NaN;
  const minIntensity =
    validIntensityData.length > 0 ? Math.min(...validIntensityData) : NaN;
  // 构建最终结果
  return {
    header: uData.header,
    data: intensityData,
    max: maxIntensity,
    min: minIntensity,
  };
}
// 定义方法
const toggleLayer = () => {
  isExpanded.value = !isExpanded.value;
};
const emit = defineEmits(["toggle-visibility", "toggle-YuecengVisibility"]);
const check3D = () => {
  if (viewerHandle.value.scene.mode == Cesium.SceneMode.SCENE3D) {
    viewerHandle.value.scene.mode = Cesium.SceneMode.SCENE2D;
    checkLabel.value = "3D";
  } else {
    viewerHandle.value.scene.mode = Cesium.SceneMode.SCENE3D;
    checkLabel.value = "2D";
  }
};
// 处理 wind-data 事件
const handleWindData = (event) => {
  windData.value = event.detail;
};
const handleTemperatureOrSalt = (event) => {
  templatureOrSalt.value = event.detail;
};
const trans = (jsonData) => {
  const header = jsonData.header;
  const originalData = jsonData.data;

  const nx = header.nx;
  const ny = header.ny;
  const la1 = header.la1;
  const lo1 = header.lo1;
  const dy = header.dy;
  const dx = header.dx;

  // 首先找到有效数据的最大值和最小值
  let minVal = Infinity,
    maxVal = -Infinity;
  for (let value of originalData) {
    if (value === null) continue; // 跳过null值
    if (value < minVal) minVal = value;
    if (value > maxVal) maxVal = value;
  }
  console.log(minVal, maxVal);
  let reformattedData = [];
  for (let y = 0; y < ny; y++) {
    for (let x = 0; x < nx; x++) {
      const index = y * nx + x;
      const lat = la1 + y * dy;
      const lon = lo1 + x * dx;
      const value = originalData[index];
      if (value === null || value == "NaN") {
        // 处理null值
        reformattedData.push({
          // lnglat: [lon, lat],
          lon: lon,
          lat: lat,
          value: 9999, // 或者可以是其他特定值，比如 'N/A'
        });
        continue;
      }
      // 线性映射value到0-1区间
      // const normalizedValue = (value - minVal) / (maxVal - minVal);
      reformattedData.push({
        // lnglat: [lon, lat],
        lon: lon,
        lat: lat,
        value: value,
      });
    }
  }
  // console.log(JSON.stringify(reformattedData, null, 2));
  return {
    data: reformattedData,
    max: maxVal,
    min: minVal,
    header: header,
  };
};
const zoomIn = () => {
  let position = viewerHandle.value.camera.position;
  let cameraHeight =
    viewerHandle.value.scene.globe.ellipsoid.cartesianToCartographic(
      position
    ).height;
  // 每次缩小 20 倍，参数可改
  let moveRate = cameraHeight / 30.0;
  viewerHandle.value.camera.moveForward(moveRate);
};
const zoomOut = () => {
  // 单击缩小
  let position = viewerHandle.value.camera.position;
  let cameraHeight =
    viewerHandle.value.scene.globe.ellipsoid.cartesianToCartographic(
      position
    ).height;
  // 每次缩小 20 倍，参数可改s
  let moveRate = cameraHeight / 30.0;
  viewerHandle.value.camera.moveBackward(moveRate);
};
function zoomInMouseDown() {
  // 长按放大
  isPressing.value = true;
  if (isPressing.value) {
    interval = setInterval(() => {
      zoomIn();
    }, 30); // 设置间隔时间以控制放大和缩小的速度
  }
}
function zoomOutMouseDown() {
  // 长按缩小
  isPressing.value = true;
  if (isPressing.value) {
    interval = setInterval(() => {
      zoomOut();
    }, 30); // 设置间隔时间以控制放大和缩小的速度
  }
}
function myMouseUp() {
  isPressing.value = false;
  clearInterval(interval);
}
const zoomToOriginal = () => {
  viewerHandle.value.camera.setView({
    destination: {
      x: -3558397.3075464107,
      y: 7300150.323537398,
      z: 2041719.4055434903,
    },
    orientation: {
      heading: 6.27669114823209,
      pitch: -1.248789382616426,
      roll: 6.283120764297309,
    },
  });
};
</script>

<style scoped>
.layer-container {
  width: 15%;
  height: 95vh;
  position: absolute;
  top: 0px;
  left: 0; /* 确保容器靠左 */
  z-index: 999;
  /* background-color: rgba(255, 255, 255, 0.3); 半透明背景色 */
  background-color: rgba(24, 44, 70, 0.8); /* 半透明背景色，深邃的科技蓝 */
  border-radius: 10px 10px 10px 0; /* 右侧圆角 */
  display: flex;
  align-items: center; /* 垂直居中内容 */
  transition: transform 0.3s ease-in-out, width 0.3s ease-in-out; /* 添加过渡效果 */
}

.items-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px; /* 为每一行之间的间距 */
  padding-left: 10px; /* 内边距，使复选框与左边框之间有空间 */
}

.item-row {
  display: flex;
  align-items: center; /* 垂直对齐 */
  width: 100%;
  transition: background-color 0.3s ease-in-out;
}

.checkbox {
  margin-right: 10px; /* 给复选框和文本之间留出一些空间 */
}

.layer-text {
  margin-right: 35px;
  text-align: left;
  flex-grow: 1; /* 让文本区域填充剩余的空间 */
  background-color: rgba(255, 255, 255, 0.5); /* 半透明背景色 */
  border-radius: 20px; /* 圆角 */
  padding: 8px 16px; /* 内边距，给文本与边框之间留出空间 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 可选：轻微的阴影以提高可读性 */
}

/* 当图层被选中时的应用样式 */
.checked-layer {
  background-color: rgba(0, 123, 255, 0.589); /* 轻微的蓝色背景 */
}

.toggle-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  border-radius: 4px;
  padding: 17px 1px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: left 0.3s ease-in-out, right 0.3s ease-in-out,
    background-color 0.3s ease;
}

.toggle-button:hover {
  background-color: rgba(255, 255, 255, 1);
}

/* 当容器被收起时的应用样式 */
.collapsed .toggle-button {
  left: 10px; /* 移动到最左侧 */
  right: auto; /* 清除右侧定位 */
}

/* 当容器展开时的应用样式 */
.layer-container:not(.collapsed) .toggle-button {
  left: auto; /* 清除左侧定位 */
  right: 1px; /* 移动到最右侧 */
}

.collapsed {
  transform: translateX(-100%); /* 容器向左移动自身宽度 */
  width: 0; /* 收缩容器宽度 */
  padding-left: 0; /* 移除内边距 */
}
.wind-data-display {
  position: absolute;
  bottom: 320px;
  right: 280px;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000; /* 确保在最上层 */
}

.wind-data-display h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.wind-data-display h4 {
  margin: 10px 0 5px 0;
  font-size: 14px;
}

.wind-data-display p {
  margin: 0;
  font-size: 12px;
}
</style>
